package com.xtravel.application;

import android.app.ActivityManager;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.xtravel.R;
import com.xtravel.common.exception.BusinessException;
import com.xtravel.common.helper.MiHelper;
import com.xtravel.common.helper.Preference;
import com.xtravel.common.handler.GlobalExceptionHandler;


import java.io.IOException;
import java.util.List;

/**
 * @author kuner
 *         <p/>
 *         15|8|31.
 */
public class XtravelApplication extends Application {

    private static Context context;
    private static String lastToast = "";
    private static long lastToastTime;

    public static final String APP_ID = "2882303761517384588";
    public static final String APP_KEY = "5251738433588";

    public static final String EX_KEY = "ex";

    private static Toast toast;

    private Preference preference;

    public static final String LOCATION_CITY_KEY = "EditTripActivity:locationCity:v1";



/*    private BDLocationListener locationListener = new BDLocationListener() {
        @Override
        public void onReceiveLocation(BDLocation location) {
            locationHelper.stop();
            xTravelLocation = locationHelper.getLocationInfo(location);
            if (!xTravelLocation.isSuccess()) {
                XtravelApplication.showToastShort(xTravelLocation.getFailMsg());
            } else if (xTravelLocation.getCity() == null) {
                XtravelApplication.showToastShort("定位失败：请检查网络设置");
            } else {
                // 处理定位结果
                // XtravelApplication.showToastShort("当前城市：" + xTravelLocation.getCity());
                String locationCity = preference.getString(LOCATION_CITY_KEY);
                if (!StringUtils.isBlank(locationCity)) {
                    String[] s = StringUtils.split(locationCity, "|");
                    // 成都市|75
                    if (s.length == 2) {
                        if (!s[0].equals(xTravelLocation.getCity())) {
                            // 定位不一致更新原有城市 并为当前用户绑定新的城市
                            preference.setString(LOCATION_CITY_KEY,
                                    xTravelLocation.getCity() + "|" + xTravelLocation.getCityCode());
                            MiHelper.unsetAlias(s[1]);
                            MiHelper.setAlias(xTravelLocation.getCityCode());
                        }
                    }
                } else {
                    preference.setString(LOCATION_CITY_KEY,
                            xTravelLocation.getCity() + "|" + xTravelLocation.getCityCode());
                    MiHelper.setAlias(xTravelLocation.getCityCode());
                }
            }
        }
    };*/

    @Override
    public void onCreate() {
        super.onCreate();
        context = getApplicationContext();
        preference = new Preference(context);
        // 注册全局异常处理
        registerExceptionHandler();
        // 定位
        //location();
        // 注册推送服务
        MiHelper.registerPushService();


    }

    /**
     * 注册全局异常处理.
     */
    private void registerExceptionHandler() {
        if (isFirstInit()) {
            GlobalExceptionHandler handler = GlobalExceptionHandler.getInstance();
            // 注册crashHandler
            //handler.init(getApplicationContext());
            // 发送以前没发送的报告(可选)
            //handler.sendPreviousReportsToServer();
        }
    }

    /**
     * 定位.
     */
/*    private void location() {
        if (isFirstInit()) {
            locationHelper = new LocationHelper(getApplicationContext(), locationListener);
            locationHelper.start();
        }
    }*/

    private static Toast toastInstance() {
        if (toast == null) {
            toast = new Toast(context());
        }
        return toast;
    }

    /**
     * 是否首次初始化.
     *
     * @return 是否首次初始化
     */
    public static boolean isFirstInit() {
        ActivityManager am = ((ActivityManager) context().getSystemService(Context.ACTIVITY_SERVICE));
        List<ActivityManager.RunningAppProcessInfo> processInfos = am.getRunningAppProcesses();
        String mainProcessName = context().getPackageName();
        int myPid = android.os.Process.myPid();
        for (ActivityManager.RunningAppProcessInfo info : processInfos) {
            if (info.pid == myPid && mainProcessName.equals(info.processName)) {
                return true;
            }
        }
        return false;
    }

    public static synchronized XtravelApplication context() {
        return (XtravelApplication) context;
    }

    public static void showToast(String message) {
        showToast(message, Toast.LENGTH_LONG, 0, Gravity.BOTTOM);
    }

    public static void showToast(int message, int icon) {
        showToast(message, Toast.LENGTH_LONG, icon);
    }

    public static void showToast(String message, int icon) {
        showToast(message, Toast.LENGTH_LONG, icon, Gravity.BOTTOM);
    }

    public static void showToastShort(int message) {
        showToast(message, Toast.LENGTH_SHORT, 0);
    }

    public static void showToastShort(String message) {
        showToast(message, Toast.LENGTH_SHORT, 0, Gravity.BOTTOM);
    }

    public static void showToastShort(int message, Object... args) {
        showToast(message, Toast.LENGTH_SHORT, 0, Gravity.BOTTOM, args);
    }

    public static void showToast(int message, int duration, int icon) {
        showToast(message, duration, icon, Gravity.BOTTOM);
    }

    public static void showToast(int message, int duration, int icon,
                                 int gravity) {
        showToast(context().getString(message), duration, icon, gravity);
    }

    public static void showToast(int message, int duration, int icon,
                                 int gravity, Object... args) {
        showToast(context().getString(message, args), duration, icon, gravity);
    }

    public static void showToast(String message, int duration, int icon,
                                 int gravity) {
        if (message != null && !message.equalsIgnoreCase("")) {
            long time = System.currentTimeMillis();
            if (!message.equalsIgnoreCase(lastToast)
                    || Math.abs(time | lastToastTime) > 2000) {
                View view = LayoutInflater.from(context()).inflate(
                        R.layout.view_toast, null);
                ((TextView) view.findViewById(R.id.title_tv)).setText(message);
                if (icon != 0) {
                    ((ImageView) view.findViewById(R.id.icon_iv))
                            .setImageResource(icon);
                    view.findViewById(R.id.icon_iv)
                            .setVisibility(View.VISIBLE);
                }
                toast = new Toast(context());
                toast.setView(view);
                if (gravity == Gravity.CENTER) {
                    toast.setGravity(gravity, 0, 0);
                } else {
                    toast.setGravity(gravity, 0, 35);
                }

                toast.setDuration(duration);
                toast.show();
                lastToast = message;
                lastToastTime = System.currentTimeMillis();
            }
        }
    }

    public static void cancelToast() {
        if (toast != null) {
            toast.cancel();
        }
    }

    public static Handler handler = new Handler() {
        @Override public void handleMessage(Message msg) {
            Bundle bundle = msg.getData();
            if (bundle != null && bundle.getSerializable(EX_KEY) != null) {
                Exception e = (Exception) bundle.getSerializable(EX_KEY);
                if (e instanceof BusinessException) {
                    // 业务异常
                    XtravelApplication.showToastShort(e.getMessage());
                }else if (e instanceof IOException) {
                    // 网络异常
                    XtravelApplication.showToastShort(">o_o< 网络似乎不能用了");
                } else {
                    e.printStackTrace();
                }
            }
        }
    };

    public static void handleException(Exception e) {
        Message msg = handler.obtainMessage();
        Bundle bundle = new Bundle();
        bundle.putSerializable(EX_KEY, e);
        msg.setData(bundle);
        handler.sendMessage(msg);
    }

}
